#include<iostream>
#include<unistd.h>
#include<arpa/inet.h>
#include<string.h>
#include<stdio.h>
#include<netinet/in.h>
#include<sys/socket.h>
#include<sys/types.h>
#define MESSAGE_LEN 1024 //maximun capacity of buffer
using namespace std;
#define PORT 8111   //server_port==client_port

int main(){
	int socket_fd;
	int ret=-1;
	char sendbuf[MESSAGE_LEN]={0,};
	char recvbuf[MESSAGE_LEN]={0,};
	struct sockaddr_in serveraddr;

	socket_fd=socket(AF_INET,SOCK_STREAM,0);
	if(socket_fd<0){
		cout<<"failed to create socket!"<<endl;
		exit(-1);
	}
	
	serveraddr.sin_family=AF_INET;
	serveraddr.sin_port=PORT;
	serveraddr.sin_addr.s_addr=inet_addr("127.0.0.1");//inet_addr: switch string to int
	ret=connect(socket_fd,(struct sockaddr *)&serveraddr,sizeof(struct sockaddr));
	if(ret<0){
		cout<<"failed to connect server!"<<endl;
                exit(-1);
	}
	
	while(1){ // while(1)==for(;;)
		memset(sendbuf,0,sizeof(sendbuf));//initialize sendbuf
		cout<<"client start to send data!"<<endl;
		cout<<"please send data:"<<endl;
		fgets(sendbuf,sizeof(sendbuf)-1,stdin); //get data from console and send data into sendbuff
		ret=send(socket_fd,sendbuf,strlen(sendbuf),0);//send data to server
		if(ret<=0){
			cout<<"failed to send data! disconnected"<<endl;
			break;
		}

		if(strcmp(sendbuf,"quit")==0){
			break;
		}

		ret=recv(socket_fd,recvbuf,MESSAGE_LEN,0);//reveive data   ret==quantity of data==recvbuf.size()-1
		recvbuf[ret]='\0';//the received data end with \0
		cout<<"received data is:"<<recvbuf<<endl;
	}
	close(socket_fd);
}
